package com.pets.springboot_petshop.service.impl;

import com.pets.springboot_petshop.entity.*;
import com.pets.springboot_petshop.mapper.*;
import com.pets.springboot_petshop.service.OrderService;
import com.pets.springboot_petshop.util.OrderNumberUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.Collections;
import java.util.List;

/**
 * @Author: wxk
 * @Email: 2089967794@qq.com
 * @Date: 2024/10/15 下午1:42 周二
 * @Description: s
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderproductMapper orderproductMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MembershiptypeMapper membershiptypeMapper;

    @Override
    public Order select(int id) {
        return orderMapper.select(id);
    }

    @Override
    public List<Order> selectuser_id(int user_id) {
        return orderMapper.selectuser_id(user_id);
    }

    @Override
    public List<Order> selectstatus(String status) {
        return orderMapper.selectstatus(status);
    }

    @Override
    public List<Order> selectOrderByDate(LocalDate date) {
        return orderMapper.selectOrderByDate(date);
    }

    @Override
    public List<Order> findAll() {
        return orderMapper.findAll();
    }

    @Override
    public int add(Order order) {
        return orderMapper.add(order);
    }

    @Override
    public int delete(int id) {
        return orderMapper.delete(id);
    }

    @Override
    public int update(Order order) {
        return orderMapper.update(order);
    }

    @Override
    public int updatestatus(Order order) {
        return orderMapper.updatestatus(order);
    }
    @Override
    @Transactional
    public Order addOrderWithProducts(Order order, List<Orderproduct> orderProducts) {
        // 生成订单编号
        String orderNumber = OrderNumberUtil.generateOrderNumber();
        order.setOrdernumber(orderNumber);

        int orderId = orderMapper.add(order);
        if (orderId == 0) {
            return null; // 插入失败
        }

        // 获取生成的订单ID
        int generatedId = order.getId();
        int userId = order.getUser_id();
        // 标记订单是否成功添加所有产品
        boolean orderSuccess = true;
        // 计算订单总金额的整数部分
        BigDecimal totalAmount = order.getTotal_amount();
        BigDecimal totalAmountIntegerPart = totalAmount.setScale(0, RoundingMode.FLOOR);

        // 遍历订单产品列表
        for (Orderproduct op : orderProducts) {
            // 根据产品ID查询产品信息
            Product product = productMapper.selectid(op.getProduct_id());
            if (product != null && product.getStock() >= op.getQuantity()) {
                // 库存充足，更新库存数量
                int newStock = product.getStock() - op.getQuantity();
                product.setStock(newStock);
                // 如果库存减少到0，更新商品状态为无库存
                if (newStock == 0) {
                    product.setState("无库存");
                    productMapper.updatestate(product);
                }
                productMapper.updatestock(product);

                // 设置订单产品信息
                op.setOrder_id(generatedId);
                // 添加订单产品
                if (orderproductMapper.add(op) == 0) {
                    orderSuccess = false;
                    break; // 订单产品添加失败
                }
            } else {
                // 库存不足，标记订单不成功
                orderSuccess = false;
                break;
            }
        }

        // 如果订单产品添加成功
        if (orderSuccess) {
            // 获取订单所属用户
            User user = userMapper.select(userId);
            if (user != null) {
                // 增加用户积分
                int newPoints = user.getIntegral() + totalAmountIntegerPart.intValue();
                user.setIntegral(newPoints);
                int rowsAffected = userMapper.updateintegral(user);
                if (rowsAffected == 0) {
                    throw new RuntimeException("更新用户积分失败");
                }

                // 查询所有会员等级
                List<Membershiptype> membershipTypes = membershiptypeMapper.findAll();
                // 找到当前会员等级
                Membershiptype currentMembership = findCurrentMembership(user.getMembership_id(), membershipTypes);

                // 找到下一个会员等级
                Membershiptype nextMembership = findNextMembership(currentMembership, membershipTypes);

                // 检查是否达到下一个更高等级的积分要求
                while (nextMembership != null && newPoints >= nextMembership.getIntegral()) {
                    user.setMembership_id(nextMembership.getId());
                    rowsAffected = userMapper.updatemembership(user);
                    if (rowsAffected == 0) {
                        throw new RuntimeException("更新用户会员等级失败");
                    }
                    currentMembership = nextMembership;
                    nextMembership = findNextMembership(currentMembership, membershipTypes);
                }
            }
            return order;
        } else {
            // 如果订单产品添加失败，回滚事务
            throw new RuntimeException("订单创建失败，库存不足或添加订单产品失败");
        }
    }

    @Override
    public int updatetk_status(Order order) {
        return orderMapper.updatetk_status(order);
    }

    @Override
    public int adminupdate(Order order) {
        return orderMapper.adminupdate(order);
    }

    @Override
    public List<Order> selectordernumber(int ordernumber) {
        return orderMapper.selectordernumber(ordernumber);
    }

    @Override
    public int batchUpdateStatus(int[] ids, String status) {
        return orderMapper.batchUpdateStatus(ids, status);
    }

    @Override
    public int admindelete(int[] ids) {
        return orderMapper.admindelete(ids);
    }

    @Override
    public List<MonthlyProfit> selectMonthlyProfit(@Param("year") int year) {
        return orderMapper.selectMonthlyProfit(year);
    }

    @Override
    public List<DailyProfit> selectDailyProfit(int year, int month) {
        return orderMapper.selectDailyProfit(year, month);
    }

    @Override
    public List<MonthlyProfit> selectMonthlyRefundRate(int year) {
        return orderMapper.selectMonthlyRefundRate(year);
    }

    @Override
    public List<MonthlyProfit> selectAnnualRefundRate(int year) {
        return orderMapper.selectAnnualRefundRate(year);
    }

    // 辅助方法：根据积分找到当前的会员等级
    private Membershiptype findCurrentMembership(int membershipId, List<Membershiptype> membershipTypes) {
        for (Membershiptype membershipType : membershipTypes) {
            if (membershipType.getId() == membershipId) {
                return membershipType;
            }
        }
        return null; // 没有找到当前会员等级
    }

    // 辅助方法：找到下一个会员等级
    private Membershiptype findNextMembership(Membershiptype currentMembership, List<Membershiptype> membershipTypes) {
        if (currentMembership == null) {
            return null;
        }
        for (Membershiptype membershipType : membershipTypes) {
            if (membershipType.getIntegral() > currentMembership.getIntegral()) {
                return membershipType;
            }
        }
        return null; // 没有找到更高的会员等级
    }
}
